<template>
  <div class="production-plan">
    <!-- 修改按钮点击事件 -->
    <el-button type="primary" @click="saveAll">保存主表单和明细</el-button>
    <h3 class="title">生产计划</h3>
    <!-- 基本信息 -->
    <el-form :model="formData" :rules="rules" label-width="120px" ref="formRef">
      <el-row :gutter="20">
        <el-col :span="7">
          <el-form-item label="*单据主题" prop="documentSubject">
            <el-input v-model="formData.documentSubject" required></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="单据编号" prop="documentNo">
            <el-input placeholder="保存后自动生成" readonly v-model="formData.documentNo"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="*关联销售合同" prop="associatedItemNumber">
            <el-input 
              placeholder="请输入" 
              v-model="formData.associatedItemNumber" 
              required
            >
              <template #suffix>
                <el-button size="mini" @click="openAssociatedItemDialog">
                  <i class="el-icon-search"></i>
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="7">
          <el-form-item label="自动生成订单" prop="automaticOrderGeneration">
            <el-radio-group v-model="formData.automaticOrderGeneration">
              <el-radio :value="false" label="否"></el-radio>
              <el-radio :value="true" label="是"></el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="*制单人员" prop="documentMaker">
            <el-input v-model="formData.documentMaker" readonly required></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="*制单日期" prop="documentationDate">
            <el-date-picker
              v-model="formData.documentationDate"
              type="date"
              required
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注 " prop="remark">
            <el-input v-model="formData.remark" type="textarea" rows="3" required></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      
    </el-form>

    <!-- 生产计划明细 -->
    <div class="detail-section">
      <h4 class="sub-title">生产计划明细</h4>
      <el-button size="small" @click="addNewRow">新增行</el-button>
      <el-table :data="planDetailsList" border style="width: 100%">
        <el-table-column label="产品名称" width="180px">
          <template #default="{ row }">
            <el-input 
              v-model="row.productName" 
              :readonly="row.isSaved"
            >
              <template #suffix>
                <el-button size="mini" @click="openProductNameDialog(row)">
                  <i class="el-icon-search"></i>
                </el-button>
              </template>
            </el-input>
          </template>
        </el-table-column>
        <el-table-column label="产品编号" width="180px">
          <template #default="{ row }">
            <el-input v-model="row.productNo" :disabled="row.productInfoFilled"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="规格型号"  width="180px">
          <template #default="{ row }">
            <el-input v-model="row.specificationModels" :disabled="row.productInfoFilled"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="单位"  width="180px">
          <template #default="{ row }">
            <el-input v-model="row.unit" :disabled="row.productInfoFilled"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="数量" width="180px">
          <template #default="{ row }">
            <el-input-number 
              v-model.number="row.orderNumber" 
              :min="0" 
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="计划开工日期" width="280px">
          <template #default="{ row }">
            <el-date-picker
              v-model="row.constructionPlannedDate"
              type="date"
              @change="checkDateOrder(row)"
            ></el-date-picker>
          </template>
        </el-table-column>
        <el-table-column label="计划完工日期" width="280px">
          <template #default="{ row }">
            <el-date-picker
              v-model="row.scheduledCompletionDate"
              type="date"
              @change="checkDateOrder(row)"
            ></el-date-picker>
          </template>
        </el-table-column>
        <el-table-column label="交货日期" width="280px">
          <template #default="{ row }">
            <el-date-picker
              v-model="row.delivery"
              type="date"
              @change="checkDateOrder(row)"
            ></el-date-picker>
          </template>
        </el-table-column>
        <el-table-column label="物料清单" width="180px">
          <template #default="{ row }">
            <el-input 
              v-model="row.billMaterials" 
              :readonly="row.isSaved"
            >
              <template #suffix>
                <el-button size="mini" @click="openBillMaterialsDialog(row)">
                  <i class="el-icon-search"></i>
                </el-button>
              </template>
            </el-input>
          </template>
        </el-table-column>
        <el-table-column label="备注" width="180px">
          <template #default="{ row }">
            <el-input v-model="row.remark" type="textarea" rows="3"></el-input>
          </template>
        </el-table-column>
        <el-table-column fixed="right"  label="操作" width="180px">
          <template #default="{ row }">
            <!-- 移除单独保存明细按钮 -->
            <el-button size="small"  type="danger" @click="deleteDetail(row)" :disabled="row.isSaved">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 附件部分 -->
    <div class="attachment-section">
      <h4 class="sub-title">附件管理</h4>
      <el-form ref="formRef" :model="formData" label-width="100px">
        <el-form-item>
          <el-upload ref="uploadRef" action="https://localhost:7269/api/FileUpload/UploadFile" :headers="headers"
            :on-success="handleSuccess" :on-error="handleError" :show-file-list="false" :http-request="customRequest">
            <el-button type="primary">选择文件</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
    </div>

    <!-- 关联项目选择对话框 -->
    <el-dialog
      v-model="associatedItemDialogVisible"
      width="500px"
      title="关联项目选择"
      append-to-body
    >
      <el-table
        :data="associatedItems"
        highlight-current-row
        border
        size="small"
        @current-change="handleAssociatedItemChange"
      >
        <el-table-column type="index" label="序号" />
        <el-table-column prop="projectName" label="项目名称" />
        <el-table-column prop="projectNum" label="项目编号" />
        <el-table-column prop="projectTime" label="日期" />
        <el-table-column prop="projectPeople" label="负责人" />
        <el-table-column prop="projectTypeId" label="项目分类" />
      </el-table>
      <template #footer>
        <el-button @click="pickAssociatedItem">确定</el-button>
      </template>
    </el-dialog>

    <!-- 产品名称选择对话框 -->
    <el-dialog
      v-model="productNameDialogVisible"
      width="500px"
      title="产品名称选择"
      append-to-body
    >
      <el-table
        :data="productNames"
        highlight-current-row
        border
        size="small"
        @current-change="handleProductNameChange"
      >
        <el-table-column type="index" label="序号" />
        <el-table-column property="productsNumber" label="产品编号" />
        <el-table-column property="productsName" label="产品名称" />
        <el-table-column property="productsNum" label="规格型号" />
        <el-table-column property="productsUnit" label="单位" />
      </el-table>
      <template #footer>
        <el-button @click="pickProductName">确定</el-button>
      </template>
    </el-dialog>

    <!-- 物料清单选择对话框 -->
    <el-dialog
      v-model="billMaterialsDialogVisible"
      width="500px"
      title="物料清单选择"
      append-to-body
    >
      <el-table
        :data="billMaterialsList"
        highlight-current-row
        border
        size="small"
        @current-change="handleBillMaterialsChange"
        height="300"
      >
        <el-table-column type="index" width="50" label="序号" />
        <el-table-column property="documentNo" label="清单编号" />
        <el-table-column property="bomSubject" label="清单主题" />
        <el-table-column property="productName" label="产品名称" />
        <el-table-column property="creator" label="添加人员" />
      </el-table>
      <template #footer>
        <el-button @click="pickBillMaterials">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
import { read, write } from '@/axios/axiosHelper';
import { useCounterStore } from '@/stores/counter'

  const store = useCounterStore();

const formRef = ref(null);

// 主表单数据
const formData = reactive({
  documentNo: "",
  documentSubject: "",
  associatedItemNumber: "",
  automaticOrderGeneration: true,
  documentMaker: store.counterStore.userName,
  documentationDate: '',
  remark: "",
  productionPlanningId: null
});

// 主表单验证规则
const rules = reactive({
  documentSubject: [
    { required: true, message: '单据主题不能为空', trigger: 'blur' }
  ],
  associatedItemNumber: [
    { required: true, message: '关联项目不能为空', trigger: 'blur' }
  ],
  documentMaker: [
    { required: true, message: '制单人员不能为空', trigger: 'blur' }
  ],
  documentationDate: [
    { required: true, message: '制单日期不能为空', trigger: 'blur' }
  ],
  remark: [
    { required: true, message: '备注不能为空', trigger: 'blur' }
  ]
});

// 明细数据列表
const planDetailsList = ref([]);

const attachments = ref([]);

// 关联项目数据
const associatedItems = ref([]);

// 产品名称数据
const productNames = ref([]);

// 物料清单数据
const billMaterialsList = ref([]);

// 对话框显示状态
const associatedItemDialogVisible = ref(false);
const currentAssociatedItem = ref({});

const productNameDialogVisible = ref(false);
const currentProductNameRow = ref(null);
const currentProductName = ref({});

const billMaterialsDialogVisible = ref(false);
const currentBillMaterialsRow = ref(null);
const currentBillMaterials = ref({});

// 获取关联项目数据
const fetchAssociatedProjects = () => {
  read.get('w-read/api/Project/ShowProject')
    .then(res => {
      associatedItems.value = res.data.data;
    })
    .catch(error => {
      console.error('获取关联项目数据失败:', error);
      ElMessage.error('获取关联项目数据失败，请检查网络或联系管理员');
    });
};

// 获取产品信息
const fetchProducts = () => {
  read.get("w2-read/api/Products/GetProducts")
    .then(res => {
      productNames.value = res.data.data;
      console.log("产品数据：", productNames.value);
      nextTick(() => {
        // 强制更新表格
      });
    })
    .catch(error => {
      console.error('获取产品信息失败:', error);
      ElMessage.error('获取产品信息失败，请检查网络或联系管理员');
    });
};

// 获取物料清单数据
const fetchBillMaterials = () => {
  read.get('l-read/api/GetValues/ZXSDMaterials')
    .then(res => {
      billMaterialsList.value = res.data.data;
      console.log("物料清单数据：", billMaterialsList.value);
      nextTick(() => {
        // 强制更新表格
      });
    })
    .catch(error => {
      console.error('获取物料清单数据失败:', error);
      ElMessage.error('获取物料清单数据失败，请检查网络或联系管理员');
    });
};

onMounted(() => {
  fetchAssociatedProjects();
  fetchProducts();
  fetchBillMaterials();
});

// 打开关联项目选择对话框
const openAssociatedItemDialog = () => {
  associatedItemDialogVisible.value = true;
};

// 当前选中的关联项目行
const handleAssociatedItemChange = (val) => {
  currentAssociatedItem.value = val;
};

// 选择关联项目
const pickAssociatedItem = () => {
  if (currentAssociatedItem.value) {
    formData.associatedItemNumber = currentAssociatedItem.value.projectName;
    associatedItemDialogVisible.value = false;
  }
};

// 打开产品名称选择对话框
const openProductNameDialog = (row) => {
  if (productNames.value.length === 0) {
    ElMessage.warning('产品信息正在加载，请稍后重试');
    return;
  }
  currentProductNameRow.value = row;
  productNameDialogVisible.value = true;
};

// 当前选中的产品名称行
const handleProductNameChange = (val) => {
  currentProductName.value = val;
};

// 选择产品名称
const pickProductName = () => {
  if (currentProductName.value && currentProductNameRow.value) {
    currentProductNameRow.value.productName = currentProductName.value.productsName;
    currentProductNameRow.value.productNo = currentProductName.value.productsNumber;
    currentProductNameRow.value.specificationModels = currentProductName.value.productsNum;
    currentProductNameRow.value.unit = currentProductName.value.productsUnit;
    currentProductNameRow.value.productInfoFilled = true; // 设置标志位，表示产品信息已填充
    productNameDialogVisible.value = false;
  }
};

// 打开物料清单选择对话框
const openBillMaterialsDialog = (row) => {
  currentBillMaterialsRow.value = row;
  billMaterialsDialogVisible.value = true;
};

// 当前选中的物料清单行
const handleBillMaterialsChange = (val) => {
  currentBillMaterials.value = val;
};

// 选择物料清单
const pickBillMaterials = () => {
  if (currentBillMaterials.value && currentBillMaterialsRow.value) {
    currentBillMaterialsRow.value.billMaterials = currentBillMaterials.value.bomSubject;
    billMaterialsDialogVisible.value = false;
  }
};

// 保存主表单和明细
const saveAll = async () => {
  if (formRef.value) {
    const isValid = await formRef.value.validate();
    if (isValid) {
      try {
        // 保存主表单
        const response = await Productionwrite.post('/z-write/api/Managerment/AddProduction', formData);
        if (response.data.code === 200) {
          formData.productionPlanningId = response.data.data.productionPlanningId;
          ElMessage.success('主表单保存成功');

          // 保存明细
          const saveDetailPromises = planDetailsList.value.map(async (row) => {
            const detailWithId = {
              ...row,
              productionPlanningId: formData.productionPlanningId
            };
            const detailResponse = await Productionwrite.post(
              '/z-write/api/Managerment/AddProductionScheduleDetail',
              detailWithId
            );
            if (detailResponse.data.code === 200) {
              row.isSaved = true;
              return true;
            } else {
              ElMessage.error(`明细保存失败：${detailResponse.data.message}`);
              return false;
            }
          });

          const results = await Promise.all(saveDetailPromises);
          if (results.every(result => result)) {
            ElMessage.success('所有明细保存成功');
          }
        } else {
          ElMessage.error(`主表单保存失败：${response.data.message}`);
        }
      } catch (error) {
        console.error('保存过程中发生错误:', error.response?.data);
        ElMessage.error('保存过程中发生错误，请检查网络或联系管理员');
      }
    }
  }
};

// 新增行
const addNewRow = () => {
  planDetailsList.value.push({
    productName: "",
    productNo: "",
    specificationModels: "",
    unit: "",
    orderNumber: 0,
    billMaterials: "",
    constructionPlannedDate: null,
    scheduledCompletionDate: null,
    delivery: null,
    remark: "",
    productionPlanningId: null,
    isSaved: false,
    productInfoFilled: false // 新增标志位，初始化为 false
  });
};

// 删除单条明细
const deleteDetail = (row) => {
  ElMessageBox.confirm('确认删除该条明细？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const index = planDetailsList.value.indexOf(row);
    if (index !== -1) {
      planDetailsList.value.splice(index, 1);
      ElMessage.success('明细删除成功');
    }
  }).catch(() => {
    ElMessage.info('取消删除');
  });
};

const headers = {}; 
const customRequest = async (options) => {
  const formData = new FormData();
  formData.append('file', options.file);
  const response = await axios.post(options.action, formData, {
    headers: headers
  });
  options.onSuccess(response.data);
  if (response.data) {
    ElMessage.success('文件上传成功');
  } else {
    ElMessage.error('文件上传失败');
  }
};

const handleError = (error) => {
  ElMessage.error('上传失败: ' + (error.response?.data?.error || error.message));
};

const uploadRef = ref(null);
const submitForm = () => {
  uploadRef.value.submit();
};

// 日期验证函数
const checkDateOrder = (row) => {
  const { constructionPlannedDate, scheduledCompletionDate, delivery } = row;
  if (constructionPlannedDate && scheduledCompletionDate && new Date(constructionPlannedDate) > new Date(scheduledCompletionDate)) {
    ElMessage.error('计划完工日期不能小于计划开工日期');
    row.scheduledCompletionDate = null;
  }
  if (scheduledCompletionDate && delivery && new Date(scheduledCompletionDate) > new Date(delivery)) {
    ElMessage.error('交货日期不能小于计划完工日期');
    row.delivery = null;
  }
};
</script>

<style scoped>
.production-plan {
  padding: 20px;
}

.title {
  text-align: center;
  margin-bottom: 20px;
}

.sub-title {
  margin: 20px 0 10px;
  font-size: 16px;
  font-weight: 500;
}

.detail-section{
  width: 100%;
}
.attachment-section {
  margin-top: 20px;
}

.el-table {
  margin-top: 10px;
}

.el-input[readonly], .el-date-editor[readonly], .el-input-number[disabled] {
  background-color: #f5f7fa;
  cursor: not-allowed;
}
</style>    